package cn.cxg.ymcc.service.impl;

import cn.cxg.ymcc.constants.BusinessConstants;
import cn.cxg.ymcc.dto.CodeDto;
import cn.cxg.ymcc.exception.GlobleException;
import cn.cxg.ymcc.service.VerfycodeService;
import cn.cxg.ymcc.util.SendSmsUitl;
import cn.cxg.ymcc.util.VerifyCodeUtils;
import com.google.errorprone.annotations.Var;
import lombok.extern.slf4j.Slf4j;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerfycodeServiceImpl implements VerfycodeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void sendCode(String phone) {
        //1.校验
        if (StringUtils.isEmpty(phone)){
            throw new GlobleException("手机号不能为空");
        }
        String key = BusinessConstants.PHONE_REGISTER+phone;

        //2.从redis中查询code
        Object obj = redisTemplate.opsForValue().get(key);
        CodeDto value = null;
        if (obj!=null){
            //3.redis中有验证码
            value=(CodeDto) obj;
            String code = value.getCode();
            if (new Date().getTime()-value.getTimer()<60*1000){
                throw new GlobleException("请勿重复发送验证码");
            }


        }else {
            //4.redis中没有验证码
            //直接生成，并存入redis中，发生给用户
            String code = VerifyCodeUtils.generateVerifyCode(4);
            long timer = new Date().getTime();

            value = new CodeDto(code, timer);

        }

        log.info("您的验证码为：{}，请在{}分钟之内使用它",value,5);
        SendSmsUitl.sendSms(phone,value.getCode());
        redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);


    }




}
